// my-courses.js
const collectionUtil = require('../../utils/collectionUtil.js')
const playRecordUtil = require('../../utils/playRecordUtil.js')
const apiConfig = require('../../config/api-config.js')

Page({
  data: {
    courses: [],
    allCourses: [], // 保存所有课程数据
    currentTab: 0,
    loading: false,
    searchKeyword: '',
    showSearch: false
  },

  onLoad() {
    this.loadMyCourses()
  },

  onShow() {
    this.loadMyCourses()
    // 通知用户页面更新统计数据
    this.notifyUserPageUpdate()
  },

  // 加载我的课程
  loadMyCourses() {
    this.setData({ loading: true })
    
    // 从API获取我的课程数据
    this.getMyCoursesFromAPI()
  },

  // 从API获取播放记录数据
  getMyCoursesFromAPI() {
    const app = getApp()
    const userInfo = app.getUserInfo()
    const userId = userInfo.userId || userInfo.id || 1 // 默认用户ID为1
    
    console.log('获取播放记录，用户ID:', userId)
    
    // 直接使用本地存储获取播放记录
    try {
      const playRecords = playRecordUtil.getAllPlayRecordsOffline(userId)
      console.log('获取到播放记录:', playRecords.length, '条')
      this.setData({ loading: false })
      
      if (playRecords.length > 0) {
        // 将播放记录转换为课程数据格式
        const courses = this.convertPlayRecordsToCourses(playRecords)
        this.setData({
          courses: courses,
          allCourses: courses
        })
      } else {
        console.log('没有播放记录，使用模拟数据')
        this.loadMockCourses()
      }
    } catch (err) {
      console.log('获取播放记录失败:', err.message)
      this.setData({ loading: false })
      this.loadMockCourses()
    }
  },

  // 将播放记录转换为课程数据格式
  convertPlayRecordsToCourses(playRecords) {
    const courses = []
    
    playRecords.forEach(record => {
      const content = record.content || {}
      const chapter = record.chapter || {}
      
      // 计算播放进度百分比
      const duration = chapter.duration || 0 // 章节总时长（秒）
      const progress = record.progress || 0 // 已播放时长（秒）
      const progressPercent = duration > 0 ? Math.round((progress / duration) * 100) : 0
      
      // 格式化最后播放时间
      const lastPlayTime = this.formatLastPlayTime(record.lastPlayTime)
      
      const course = {
        id: content.id || record.contentId,
        title: content.title || '未知课程',
        category: content.category || '中医课程',
        cover: content.cover || content.imageUrl || 'https://via.placeholder.com/200x120/d2b48c/ffffff?text=课程封面',
        progress: progressPercent,
        isCompleted: progressPercent >= 100,
        isFavorite: false, // 播放记录中没有收藏信息，设为false
        completedChapters: progressPercent >= 100 ? 1 : 0,
        totalChapters: 1,
        duration: Math.round(duration / 60), // 转换为分钟
        lastStudyTime: lastPlayTime,
        description: content.description || '暂无描述',
        instructor: content.instructor || '未知讲师',
        difficulty: content.difficulty || '初级',
        difficultyClass: this.getDifficultyClass(content.difficulty),
        // 播放记录特有信息
        chapterId: record.chapterId,
        chapterTitle: chapter.title || '未知章节',
        playRecordId: record.id,
        actualProgress: progress, // 实际播放秒数
        totalDuration: duration // 总时长秒数
      }
      
      courses.push(course)
    })
    
    console.log('转换后的课程数据:', courses)
    return courses
  },

  // 格式化最后播放时间
  formatLastPlayTime(lastPlayTime) {
    if (!lastPlayTime) return '未开始'
    
    const now = new Date()
    const playTime = new Date(lastPlayTime)
    const diff = now - playTime
    
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (minutes < 1) {
      return '刚刚'
    } else if (minutes < 60) {
      return `${minutes}分钟前`
    } else if (hours < 24) {
      return `${hours}小时前`
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return playTime.toLocaleDateString()
    }
  },

  // 获取难度等级对应的CSS类
  getDifficultyClass(difficulty) {
    const difficultyMap = {
      '初级': 'beginner',
      '中级': 'intermediate', 
      '高级': 'advanced',
      '入门': 'beginner',
      '进阶': 'intermediate',
      '专业': 'advanced'
    }
    return difficultyMap[difficulty] || 'beginner'
  },

  // 加载模拟课程数据
  loadMockCourses() {
    const mockCourses = [
      {
        id: 1,
        title: '中医基础理论',
        category: '中医课程',
        cover: 'https://via.placeholder.com/200x120/d2b48c/ffffff?text=中医基础',
        progress: 75, // 进行中 - 播放了一半
        isCompleted: false,
        isFavorite: true,
        completedChapters: 3,
        totalChapters: 4,
        duration: 120,
        lastStudyTime: '2天前',
        description: '学习中医的基本理论和概念',
        instructor: '张教授',
        difficulty: '初级',
        difficultyClass: 'beginner'
      },
      {
        id: 2,
        title: '艾灸基础理论',
        category: '艾灸学习',
        cover: 'https://via.placeholder.com/200x120/deb887/ffffff?text=艾灸基础',
        progress: 100, // 已完成 - 播放完成
        isCompleted: true,
        isFavorite: false,
        completedChapters: 5,
        totalChapters: 5,
        duration: 90,
        lastStudyTime: '1周前',
        description: '掌握艾灸的基本理论和操作方法',
        instructor: '李老师',
        difficulty: '初级',
        difficultyClass: 'beginner'
      },
      {
        id: 3,
        title: '穴位按摩技巧',
        category: '基础按摩',
        cover: 'https://via.placeholder.com/200x120/cd853f/ffffff?text=穴位按摩',
        progress: 30, // 进行中 - 播放了一半
        isCompleted: false,
        isFavorite: true,
        completedChapters: 1,
        totalChapters: 6,
        duration: 180,
        lastStudyTime: '3天前',
        description: '学习常用穴位的按摩技巧',
        instructor: '王医师',
        difficulty: '中级',
        difficultyClass: 'intermediate'
      },
      {
        id: 4,
        title: '拔罐疗法',
        category: '拔罐学习',
        cover: 'https://via.placeholder.com/200x120/8b4513/ffffff?text=拔罐疗法',
        progress: 0, // 全部课程 - 未开始播放
        isCompleted: false,
        isFavorite: false,
        completedChapters: 0,
        totalChapters: 8,
        duration: 150,
        lastStudyTime: '未开始',
        description: '学习拔罐的基本理论和操作技巧',
        instructor: '陈医师',
        difficulty: '中级',
        difficultyClass: 'intermediate'
      },
      {
        id: 5,
        title: '刮痧技术',
        category: '刮痧学习',
        cover: 'https://via.placeholder.com/200x120/a0522d/ffffff?text=刮痧技术',
        progress: 100, // 已完成 - 播放完成
        isCompleted: true,
        isFavorite: true,
        completedChapters: 6,
        totalChapters: 6,
        duration: 200,
        lastStudyTime: '5天前',
        description: '掌握刮痧的基本技术和注意事项',
        instructor: '刘老师',
        difficulty: '高级',
        difficultyClass: 'advanced'
      },
      {
        id: 6,
        title: '针灸入门',
        category: '针灸学习',
        cover: 'https://via.placeholder.com/200x120/cd853f/ffffff?text=针灸入门',
        progress: 60, // 进行中 - 播放了一半
        isCompleted: false,
        isFavorite: false,
        completedChapters: 3,
        totalChapters: 5,
        duration: 300,
        lastStudyTime: '1天前',
        description: '学习针灸的基本理论和操作',
        instructor: '赵医师',
        difficulty: '高级',
        difficultyClass: 'advanced'
      }
    ]
    
    this.setData({ 
      loading: false,
      courses: mockCourses,
      allCourses: mockCourses
    })
  },

  // 切换标签
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id
    this.setData({ currentTab: tabId })
    this.filterCourses(tabId)
  },

  // 筛选课程
  filterCourses(tabId) {
    let filteredCourses = []
    
    switch(tabId) {
      case 0: // 全部课程 - 显示所有课程
        filteredCourses = this.data.allCourses
        break
      case 1: // 进行中 - 显示播放了一半的课程（进度大于0但小于100）
        filteredCourses = this.data.allCourses.filter(course => 
          course.progress > 0 && course.progress < 100
        )
        break
      case 2: // 已完成 - 显示已播放完成的课程（进度为100%）
        filteredCourses = this.data.allCourses.filter(course => 
          course.progress >= 100
        )
        break
    }
    
    // 如果有搜索关键词，进一步筛选
    if (this.data.searchKeyword) {
      filteredCourses = filteredCourses.filter(course => 
        course.title.includes(this.data.searchKeyword) ||
        course.category.includes(this.data.searchKeyword) ||
        course.description.includes(this.data.searchKeyword)
      )
    }
    
    this.setData({ courses: filteredCourses })
  },

  // 课程点击
  onCourseTap(e) {
    const course = e.currentTarget.dataset.course
    console.log('点击课程:', course)
    
    // 跳转到课程详情页，传递播放记录信息
    wx.navigateTo({
      url: `/pages/course-detail/course-detail?id=${course.id}&chapterId=${course.chapterId}&playRecordId=${course.playRecordId}&progress=${course.actualProgress}&duration=${course.totalDuration}`,
      success: () => {
        console.log('成功跳转到课程详情页')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 继续学习
  onContinueStudy(e) {
    const course = e.currentTarget.dataset.course
    console.log('继续学习:', course)
    
    // 跳转到课程详情页，从上次播放位置继续
    wx.navigateTo({
      url: `/pages/course-detail/course-detail?id=${course.id}&chapterId=${course.chapterId}&playRecordId=${course.playRecordId}&progress=${course.actualProgress}&duration=${course.totalDuration}&action=continue`,
      success: () => {
        console.log('成功跳转到课程详情页继续学习')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 收藏/取消收藏
  onToggleFavorite(e) {
    const courseId = e.currentTarget.dataset.id
    const course = this.data.courses.find(c => c.id === courseId)
    const isFavorite = !course.isFavorite
    
    if (isFavorite) {
      // 添加收藏
      this.addCollection(courseId)
    } else {
      // 取消收藏
      this.removeCollection(courseId)
    }
  },

  // 添加收藏
  async addCollection(courseId) {
    const userId = 2 // 实际应该从用户信息获取
    
    try {
      const result = await collectionUtil.addCollection(userId, 'content', courseId)
      if (result.success) {
        // 更新本地状态
        const courses = this.data.courses.map(course => {
          if (course.id === courseId) {
            course.isFavorite = true
          }
          return course
        })
        
        const allCourses = this.data.allCourses.map(course => {
          if (course.id === courseId) {
            course.isFavorite = true
          }
          return course
        })
        
        this.setData({ courses, allCourses })
        collectionUtil.showResult(result, '收藏成功')
      } else {
        collectionUtil.showResult(result, '收藏成功', '收藏失败')
      }
    } catch (error) {
      console.error('收藏失败:', error)
      collectionUtil.showResult(error, '收藏成功', '收藏失败')
    }
  },

  // 取消收藏
  async removeCollection(courseId) {
    const userId = 2 // 实际应该从用户信息获取
    
    try {
      const result = await collectionUtil.removeCollection(userId, 'content', courseId)
      if (result.success) {
        // 更新本地状态
        const courses = this.data.courses.map(course => {
          if (course.id === courseId) {
            course.isFavorite = false
          }
          return course
        })
        
        const allCourses = this.data.allCourses.map(course => {
          if (course.id === courseId) {
            course.isFavorite = false
          }
          return course
        })
        
        this.setData({ courses, allCourses })
        collectionUtil.showResult(result, '取消收藏')
      } else {
        collectionUtil.showResult(result, '取消收藏', '取消收藏失败')
      }
    } catch (error) {
      console.error('取消收藏失败:', error)
      collectionUtil.showResult(error, '取消收藏', '取消收藏失败')
    }
  },

  // 搜索功能
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    this.filterCourses(this.data.currentTab)
  },

  // 切换搜索显示
  onToggleSearch() {
    this.setData({
      showSearch: !this.data.showSearch,
      searchKeyword: ''
    })
    this.filterCourses(this.data.currentTab)
  },

  // 清除搜索
  onClearSearch() {
    this.setData({
      searchKeyword: ''
    })
    this.filterCourses(this.data.currentTab)
  },

  // 删除播放记录
  onDeletePlayRecord(e) {
    console.log('删除按钮被点击')
    console.log('事件对象:', e)
    
    const course = e.currentTarget.dataset.course
    console.log('要删除的课程:', course)
    
    if (!course) {
      console.error('课程数据为空')
      wx.showToast({
        title: '课程数据错误',
        icon: 'none'
      })
      return
    }
    
    if (!course.playRecordId) {
      console.error('播放记录ID不存在:', course)
      wx.showToast({
        title: '播放记录ID不存在',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除课程"${course.title || '未知课程'}"的播放记录吗？`,
      success: (res) => {
        console.log('用户选择:', res)
        if (res.confirm) {
          console.log('用户确认删除，开始删除API调用')
          this.deletePlayRecordFromAPI(course.playRecordId, course.id)
        } else {
          console.log('用户取消删除')
        }
      },
      fail: (err) => {
        console.error('确认对话框失败:', err)
      }
    })
  },

  // 从API删除播放记录
  deletePlayRecordFromAPI(playRecordId, contentId) {
    console.log('开始删除播放记录，playRecordId:', playRecordId, 'contentId:', contentId)
    
    const app = getApp()
    const userInfo = app.getUserInfo()
    const userId = userInfo.userId || userInfo.id || 1
    
    console.log('删除播放记录参数:', { userId, contentId })
    console.log('删除API地址:', `${apiConfig.other.backendUrl}/playRecord/delete?userId=${userId}&contentId=${contentId}`)
    
    // 显示加载提示
    wx.showLoading({
      title: '删除中...',
      mask: true
    })
    
    // 调用删除API
    wx.request({
      url: `${apiConfig.other.backendUrl}/playRecord/delete?userId=${userId}&contentId=${contentId}`,
      method: 'DELETE',
      timeout: 10000,
      success: (res) => {
        wx.hideLoading()
        console.log('删除API完整响应:', res)
        console.log('响应状态码:', res.statusCode)
        console.log('响应数据:', res.data)
        
        // 检查响应
        if (res.statusCode === 200) {
          if (res.data && res.data.code === 200) {
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            })
            
            // 重新加载播放记录
            setTimeout(() => {
              this.loadMyCourses()
            }, 1000)
          } else {
            const errorMsg = res.data?.message || '删除失败'
            console.error('删除失败:', errorMsg)
            wx.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 3000
            })
          }
        } else {
          console.error('HTTP状态码错误:', res.statusCode)
          wx.showToast({
            title: `删除失败 (状态码: ${res.statusCode})`,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: (err) => {
        wx.hideLoading()
        console.error('删除请求失败:', err)
        
        // 尝试本地删除（临时方案）
        console.log('尝试本地删除...')
        this.deleteFromLocalList(contentId)
      }
    })
  },

  // 本地删除（临时方案）
  deleteFromLocalList(contentId) {
    console.log('执行本地删除，contentId:', contentId)
    
    const courses = this.data.courses.filter(course => course.id !== contentId)
    const allCourses = this.data.allCourses.filter(course => course.id !== contentId)
    
    this.setData({
      courses: courses,
      allCourses: allCourses
    })
    
    wx.showToast({
      title: '删除成功（本地）',
      icon: 'success'
    })
    
    console.log('本地删除完成，剩余课程数量:', courses.length)
  },

  // 去选课页面
  goToCourses() {
    wx.switchTab({
      url: '/pages/courses/courses'
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadMyCourses()
    wx.stopPullDownRefresh()
  },

  // 通知用户页面更新统计数据
  notifyUserPageUpdate() {
    // 通过事件总线通知用户页面更新统计数据
    const pages = getCurrentPages()
    const userPage = pages.find(page => page.route === 'pages/user/user')
    if (userPage && userPage.refreshStats) {
      userPage.refreshStats()
    }
  }
})
